<?php
/**
 * Created by PhpStorm.
 * User: wangsong
 * Time: 2018/5/28 10:49
 */

namespace App\Project\Version;

use Illuminate\Foundation\Console\ClosureCommand;

abstract class AbstractPublish
{
    protected $command;

    public function __construct(ClosureCommand $command)
    {
        $this->command = $command;
    }

    public function migrate()
    {
        $this->command->call('migrate');
    }

    /**
     * @param       $packages
     * @param array $options
     * @return Composer
     */
    public function composer($packages, $options = [])
    {
        $composer = new Composer();

        return $composer->packages($packages)->setOptions($options);
    }

    public function external(Executable $command)
    {
        passthru($command->execute());
    }

    public function handle($behavior)
    {
        $flag_file = storage_path('version/flags/') . class_basename($this);

        if ($behavior == 'install') {
            if (!file_exists($flag_file)) {
                $this->$behavior();
                $this->after();
                \File::put($flag_file, 'completed');
            }
        } else {
            if (file_exists($flag_file)) {
                $this->$behavior();
                \File::delete($flag_file);
            }
        }
    }

    public function after()
    {
        $this->command->call('route:cache');

        if (!file_exists(public_path('storage'))) {
            $this->command->call('storage:link');
        }
    }

    abstract public function install();

    abstract public function rollback();
}